//
//  BackViewController.m
//  iGSS
//
//  Created by Antony Chazapis on 1/20/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "BackViewController.h"

#import "RootViewController.h"
#import "FormattingUtilities.h"

@implementation BackViewController

@synthesize delegate;
@synthesize navigationBar;
@synthesize dataSourceArray;

- (void)viewDidLoad {
    [super viewDidLoad];

	self.navigationBar.topItem.title = LocalizedString(@"Back to");
	self.navigationBar.topItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelPressed:)] autorelease];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)viewDidUnload {
	self.dataSourceArray = nil;
}

- (void)dealloc {
	// XXX Release dataSourceArray?...
    [super dealloc];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ([self.dataSourceArray count] - 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"cellTypeBack";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
	// XXX Can the dataSourceArray be released (the views inside), while we are here?...
	RootViewController *rootViewController = [self.dataSourceArray objectAtIndex:(([self.dataSourceArray count] - indexPath.row) - 2)];
	cell.textLabel.text = rootViewController.title;
	
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	RootViewController *rootViewController = [self.dataSourceArray objectAtIndex:(([self.dataSourceArray count] - indexPath.row) - 2)];
	[self.delegate backEnded:(UIViewController *)rootViewController];
}

#pragma mark Private methods

- (void)cancelPressed:(id)sender {
	[self.delegate backEnded:nil];
}

@end
